package dev.guide.multithread;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import dev.guide.R;

public class MultithreadActivity extends Activity implements OnClickListener {
	private TextView mInfo;
	private static int mCount = 0;
	private Thread mThreadA = null;
	private static final String TAG = "MultithreadActivity";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.multithread);
		findViewById(R.id.start_thead).setOnClickListener(this);
		findViewById(R.id.interrupt_thread).setOnClickListener(this);
		mInfo = (TextView) findViewById(R.id.textview_showinfo);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.start_thead:
			mThreadA = new Thread(new ThreadA());
			mThreadA.setUncaughtExceptionHandler(new MyExceptionHandler());
			mThreadA.start();
			break;
		case R.id.interrupt_thread:
			if (mThreadA != null) {
				mThreadA.interrupt();
			}
			Log.v(TAG, "mThreadA.getState()=" + mThreadA.getState());
			break;
		}
	}

	private final Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			mInfo.setText(String.valueOf(mCount));
		}

	};

	private class ThreadA implements Runnable {
		@Override
		public void run() {
			while (!Thread.currentThread().isInterrupted()) {
				mCount++;
				if (mCount % 100 == 0) {
					mHandler.sendEmptyMessage(0);
				}
			}
			int i = 10/0;
		}
	}
	
	private class MyExceptionHandler implements Thread.UncaughtExceptionHandler {

		@Override
		public void uncaughtException(Thread thread, Throwable ex) {
			Log.e(TAG, "uncaughtException:"+ex.getMessage());			
		}
		
	}

}
